Javascript Functions


Published on: July 03, 2021 By T.Andrew Rayan

A function is a set of codes that is used to perform a task. It will execute the set of codes whenever the function is called.

Syntax 1:

// Function without parameters
function function_name(){
}

Syntax 2:

// Function with parameters.
function function_name(parameter1, parameter2, ...) {
}

The function is the keyword of the javascript to mention that its a function. In place of function_name, we replace a user defined name for the function. Usually the name of the function should be the operation that function does.

The parameter1 and parameter2 are the parameters passed to the function. The parameters are seperated by comma. We can have any number of parameters. Its used to get some values from the function call to be used by the set of codes.

The set of codes are the one that is enclosed inside the curly brackets {}. Usually, we call it as block of code.

Example

Here print is the function name. The message is the parameter variable. Here we call the function with the name of the function and a string Helloworld as parameter.

Now the message variable receives Helloworld value. Now the block of code will print the value in message parameter variable.

How to call a function?

When calling a function, we should mention the function name. We should also pass the exact number of parameters that the function has.

If we have defined the function with no parameters, then we have to call the function with no paramters. If we have defined the funtion with 2 parameters, then we have to call the function with 2 parameters.

Function with return value:

The function, after performing set of codes can also return the resulting value.

Example

In the above example, we have a function with name add that has value1 and value2 as parameters. It adds the value1 and value2 parameters and return the resulting value with the build-in keyword return.

We call the function add with parameters 10 and 20. The add function will be returning the value 30. The value is assigned to the variable result and printed to the console.

The modern way of representing a function is the arrow function. This can be referred in this "link".

Tips for writing a function:

*) A function name should match the operation that it does.

*) The best practise is that a function should perform only one task. It should be responsible to perform a single task.

*) The name of the function should be camelCase. Example getUsers, printMessage.

*) Keep the function as small as possible.


Most Read